package incidencies.android.es;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

public class IncidenciesUpdate extends AsyncTask<Context, Integer, Context> {
	@Override
	protected Context doInBackground(Context... contexts) {
		try {
			// TransParser parser=new
			// TransParser("http://www.gencat.cat/rodalies/incidencies_rodalies_rss_r13_ca_ES.xml");
			TransParser parser = new TransParser(
					"http://dl.dropbox.com/u/9360391/incidencies_rodalies_rss_r13_ca_ES.xml");
			List<Incidencia> lista = parser.parse();
			Iterator<Incidencia> i = lista.iterator();
			//Afegit totes les incidencies en un buffer
			StringBuffer totesLesIncidencies=new StringBuffer();
			while (i.hasNext()) {
				Incidencia in = i.next();
				Log.v("Update inc.", in.toString());
				totesLesIncidencies.append(in.getUpdateDate()+in.getTitle()+"\r\n");
			}
			if (totesLesIncidencies.length()<5){
				totesLesIncidencies.append("Sin incidencias");
			}
				SharedPreferences preferencies = PreferenceManager.getDefaultSharedPreferences(contexts[0]);
				SharedPreferences.Editor editor = preferencies.edit();
				editor.putString("INCIDENCIES", totesLesIncidencies.toString());
				editor.commit();
				Log.v("Update inc.","Afegides les preferencies");
			
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public String convertStreamToString(InputStream is) throws IOException {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {
			return "";
		}
	}
}
